package com.fashion.server.common;

import org.apache.log4j.HTMLLayout;
import org.apache.log4j.spi.LoggingEvent;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by WangXin on 2016/12/29.
 */
public class HefanLogHtmlLayout extends HTMLLayout {

    private StringBuffer sbuf;
    private String ips;

    public HefanLogHtmlLayout(){
//		sbuf = new StringBuffer(128);
        List<String> ipArr = getIps();
        ips = ipArr.toString();
    }

    @Override
    public String format(LoggingEvent event) {
//		sbuf.setLength(0);
//        sbuf.append("错误等级："+event.getLevel().toString()+"===");
//        sbuf.append("错误原因："+event.getMessage().toString()+"===");
//        sbuf.append("错误所在类"+event.getLocationInformation().getClassName()+"===");
//        sbuf.append("错误方法所在："+event.getLocationInformation().getMethodName()+"===");
//        sbuf.append("错误行:"+event.getLocationInformation().getLineNumber());
//        return sbuf.toString();
        StringBuffer sb = new StringBuffer();
        sb.append("<tr><td colspan=\"2\">服务器IP地址</td>");
        sb.append("<td colspan=\"3\">");
        sb.append(ips);
        sb.append("</td></tr>");
        sb.append( super.format(event));
        return sb.toString();
    }

    @Override
    public String getContentType() {
        return  "text/html;charset=utf-8" ;
    }

    @Override
    public boolean ignoresThrowable() {
        return false;
    }

    private static List<String> getIps(){
        List<String> ips = new ArrayList<String>();
        Enumeration<?> e1;
        try {
            e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) e1.nextElement();
                Enumeration<?> e2 = ni.getInetAddresses();
                while (e2.hasMoreElements()) {
                    InetAddress ia = (InetAddress) e2.nextElement();
                    if (ia instanceof Inet6Address)
                        continue;
                    String ip = ia.getHostAddress();
                    if(ip.equals("127.0.0.1")){
                        continue;
                    }
                    ips.add(ip);
                }
            }
        } catch (SocketException e) {
        }
        return ips;
    }




}
